<template>
  <div class="edit">
    <div class="container">
      <div class="main">
		<p class="title">账号信息</p>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="90" class="box">
          <!-- 登录账号 -->
          <FormItem prop="userName" label='登录账号：'>
            <Input v-model.trim="formValidate.userName" placeholder="请输入登录账号" style="width: 500px" autocomplete="off"  id='userName' @on-keyup="formValidate.userName = formValidate.userName.replace(/[^\w_]/g,'');" maxlength="64"/>
          </FormItem>
          <!-- 更改密码 -->
          <FormItem  v-if="flag" prop="passWord"  label='更改密码：'>
              <Input v-model.trim="formValidate.passWord" :placeholder="tip" style="width: 500px;border-radius:5px;" type="password" autocomplete="new-password"></Input>
              <img src="../../../../../assets/images/close.png" @click="handlePassword" alt="" class="eye">
              <br />
              <span style="color:#ff9966">（备注：未填写更改密码时,不修改密码）</span>
          </FormItem>
            <FormItem v-if="!flag" prop="passWord"  label='更改密码：'>
              <Input v-model.trim="formValidate.passWord" :placeholder="tip" style="width: 500px;border-radius:5px;" type="text" autocomplete="new-password"></Input>
              <img src="../../../../../assets/images/open.png" @click="handlePassword" alt="" class="eye">
          </FormItem>
          <FormItem prop="phone" label='手机号码：'>
            <Input v-model.trim="formValidate.phone" placeholder="请输入用户手机号" number style="width: 500px" autocomplete="off"  id='phone' maxlength="11"/>
          </FormItem>
          <!-- 用户昵称 -->
          <FormItem prop="niceName" label='用户昵称：'>
            <Input v-model.trim="formValidate.niceName" placeholder="请填写用户昵称" style="width: 500px" maxlength="10"/>
          </FormItem>
          <FormItem label='用户头像：'>
              <div class="input">
                  <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
                    <div v-if="item.status === 'finished'">
                      <img :src="item.url">
                      <div class="demo-upload-list-cover">
                        <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                      </div>
                    </div>
                    <div v-else>
                      <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </div>
                  </div>
                  <Upload
                    v-show="uploadList.length ==0"
                    ref="upload"
                    :show-upload-list="false"
                    :default-file-list="defaultList"
                    :on-success="handleSuccess"
                    :format="['jpg','jpeg','png']"
                    :max-size="2000"
                    :on-format-error="handleFormatError"
                    :on-exceeded-size="handleMaxSize"
                    :before-upload="handleBeforeUpload"
                    multiple
                    type="drag"
                    :action="uploadUrl"
                    :headers="fromData"
                    :data="uploadData"
                    style="display: inline-block;width:60px;"
                  >
                  <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="ios-camera" size="20"></Icon>
                  </div>
                </Upload>
                <Modal title="预览图片" v-model="visible" footer-hide  :transfer="false">
                  <img :src=" uploadList[0].url " v-if="visible" style="width: 100%">
                </Modal>
              </div>
          </FormItem>
           <!-- 用户身份 -->
          <FormItem label='用户身份：'>
            <div>
              <Select class="w-select-identity" placeholder="用户身份" v-model="identity" disabled style="width:500px;">
                <Option v-for="item in identityList" :value="item.id" :key="item.id" style='text-align:center;'>{{item.name}}</Option>
              </Select>
            </div>
          </FormItem>
          <!-- 用户所属 -->
          <FormItem label='用户所属：'>
            <div>
              <Select
                class="w-select"
                @on-change="changeProvince"
                placeholder="省"
                v-model="provinceId"
                disabled
                v-if="identity >= 2 || identity === 5"
              >
                <!-- <Option value="0">全国</Option> -->
                <Option v-for="item in provinceList" :value="item.id" :key="item.id" style='text-align:center;'>{{item.name}}</Option>
              </Select>
              <Select
                class="w-select"
                @on-change="changeCity"
                placeholder="市"
                v-model="cityId"
                disabled
                v-if="identity >= 3 || identity === 5"
              >
                <Option v-for="(item) in cityList" :value="item.id" :key="item.id" style='text-align:center;'>{{item.name}}</Option>
              </Select>
              <Select
                class="w-select"
                @on-change="changeArea"
                placeholder="区/县"
                v-model="areaId"
                disabled
                v-if="identity >= 4 || identity === 5"
              >
                <Option v-for="item in areaList" :value="item.id" :key="item.id">{{item.name}}</Option>
              </Select>
              <Select
                class="w-select-hos"
                placeholder="医院"
                v-model="hospitalId"
                disabled
                v-if="identity == 5"
              >
                <Option v-for="item in hospitalList" :value="item.id" :key="item.id" style='text-align:center;'>{{item.orgName}}</Option>
              </Select>
            </div>
          </FormItem>
          <!-- 所属科室 -->
          <FormItem label='所属科室：' v-if="hospitalId != null">
            <Select
              class="w-select"
              placeholder="科室"
              v-model="department"
              v-if="hospitalId != null"
              clearable
            >
              <Option
                v-for="(item,index) in departmentList"
                :value="item"
                :key="index"
                style='text-align:center;'
              >{{item}}</Option>
            </Select>
          </FormItem>
          <!-- 是否开启 -->
          <FormItem  label='是否开启：'>
            <iSwitch v-model="switch1" size="large">
              <span slot="open">启用</span>
              <span slot="close">禁用</span>
            </iSwitch>
          </FormItem>
        </Form>
      </div>
      <div style="border-top: 1px dashed #999; margin-right:-32px"></div>
      <!-- 保存 -->
      <div style="width:100%;text-align:center;padding: 20px 0px;">
        <Button type="primary" @click="save('formValidate')" :disabled='disabledSave' style="width:75px;height:35px;">
          <Icon type="ios-checkmark" style="margin-right: 5px" />保存
        </Button>
        <Button @click="back" style="width:75px;height:35px;">
          <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
        </Button>
      </div>
    </div>
  </div>
</template>
<script>
import api from "@/api/commonApi";
import code from "@/configs/base.js";
import cookie from "../../../../../utils/cookie.js";
export default {
  data() {
    const validatePassword = (rule, value, callback) => {
         if (value === '') {
            callback(new Error('请输入新密码'));
         } else {
              //6-20位包含字符、数字和特殊字符
              var ls = 0;
          if (this.formValidate.passWord !== '') {
              if(this.formValidate.passWord.match(/([a-z])+/)){
                ls++;
              }
              if(this.formValidate.passWord.match(/([0-9])+/)){
                ls++;
              }
              if(this.formValidate.passWord.match(/([A-Z])+/)){
                ls++;
              }
              if(this.formValidate.passWord.match(/([\W])+/) && !this.formValidate.passWord.match(/(![\u4E00-\u9FA5])+/)){ 
                ls++;
              }
              if(this.formValidate.passWord.length<8 || this.formValidate.passWord.length>16 ){
                  callback(new Error('要求8-16位字符'));
                  ls=0;
              }
              if(this.formValidate.passWord.match(/([\u4E00-\u9FA5])+/)){
                  callback(new Error('不能包含中文字符'));
                  ls=0;
              }
            if(cookie.getCookie("levelp") ==1){
                  switch (ls) {
                      case 0: this.passwordPercent = 0;callback(new Error('请设置登录密码(密码需8-16位)'));break;
                      case 3:
                      case 4: this.passwordPercent = 100;break;
                      default: this.passwordPercent = 0;break;
                  }
            }else if(cookie.getCookie("levelp") == 2){
                switch (ls) {
                  case 0: this.passwordPercent = 0;callback(new Error('密码需8-16位,包含字母和数字或特殊符号'));break;
                  case 1: this.passwordPercent = 33;callback(new Error('密码需8-16位,包含字母和数字或特殊符号'));break;
                  case 3:
                  case 4: this.passwordPercent = 100;break;
                  default: this.passwordPercent = 0;break;
              }
            }else if(cookie.getCookie("levelp") ==3){
                switch (ls) {
                  case 0: this.passwordPercent = 0;callback(new Error('密码需8-16位,包含字母和数字或特殊符号'));break;
                  case 1: this.passwordPercent = 33;callback(new Error('密码需8-16位,包含大小字母和数字或特殊符号'));break;
                  case 2: this.passwordPercent = 66;callback(new Error('密码需8-16位,包含大小字母和数字或特殊符号'));break;
                  case 3:
                  case 4: this.passwordPercent = 100;break;
                  default: this.passwordPercent = 0;break;
              }
            }
          }
          callback();
     }
    };
    return {
      showDialog: false,
      tip:'',
      flag: true,
      leng:true,
      changer:0,
      passwordPercent:0,
      formValidate:{
        userName:"",
        niceName:"",
        passWord:"",
        phone:"",
      },
      // 验证条件
      ruleValidate:{
        userName:[
          {
            // 是否校验
            required: true,
            // 提示文字
            message: "请输入登录账号",
            // 触发事件
            trigger: "change"
          }
        ],
        // 登录密码
				passWord:[
					{
						// 是否校验
						required: false,
						// 提示文字
						validator: validatePassword,
						// 触发事件
            trigger: "blur",
					}
				],
        niceName:[
          {
            // 是否校验
            required: true,
            // 提示文字
            message: "请输入用户昵称",
            // 触发事件
            trigger: "blur"
          }
        ],
        phone:[
          {
            // type: 'number',
            // 是否校验
            required: true,
            // 提示文字
            message: "请输入用户手机号码",
            // 触发事件
            trigger: "blur"
          }
        ]
      },
      switch1: true,
      // 账号
      text: "",
      // 密码
      passWord: "",
      // 姓名
      name: "",
      // 手机号码
      phone: "",
      // 昵称
      niceName: "",
      // 机构名称
      Organizationname: "",
      //用户角色
      role: "",
      // 备注
      remarks: "",
      // 机构名称列表
      hospial: [
        {
          value: "New York",
          label: "New York"
        }
      ],
      //用户角色列表
      roleList: [
        {
          value: "New York",
          label: "New York"
        }
      ],
      // 默认列表
      defaultList: [],
      // 图片名称
      imgName: "",
      // modal显示
      visible: false,
      uploadList: [],
      // id: sessionStorage.getItem("appid"),
      uploadModal: true,
      uploadData: {
        json: '{"urlCode":"' + code.urlCode.userImage + '"}'
      },
      activeUploadId: "5c2bf345-b973-4ffd-a52e-87bb9c1d2b72",
      uploadUrl: api.fileAll,
      images: "",

      identityList: [
        { id: 1, name: "超级管理员" },
        { id: 2, name: "省级管理员" },
        { id: 3, name: "市级管理员" },
        { id: 4, name: "区级管理员" },
        { id: 5, name: "机构配置管理员" }
      ],
      identity: 5,
      provinceList: [],
      cityList: [],
      areaList: [],
      hospitalList: [],
      provinceId: null,
      cityId: null,
      areaId: null,
      hospitalId: null,
      identityCoding: null,
      disabledSave: false,
      departmentList: [],
      department: null
    };
  },
  mounted() {
       console.log(this.formValidate.passWord )
       console.log(this.passWord)
  },
  created() {
    if(cookie.getCookie("levelp") == 1){
        this.tip = "请设置登录密码(密码需8-16位)"
    }else if(cookie.getCookie("levelp") == 2){
        this.tip = "请设置登录密码(密码需8-16位,包含字母和数字或特殊符号)"
    }else{
        this.tip = "请设置登录密码(密码需8-16位,包含大小字母和数字或特殊符号)"
    }
    this.province = this.$route.query.province
      ? parseInt(this.$route.query.province)
      : null;
    this.city = this.$route.query.city
      ? parseInt(this.$route.query.city)
      : null;
    this.area = this.$route.query.area
      ? parseInt(this.$route.query.area)
      : null;
    this.hospital = this.$route.query.hospital
      ? this.$route.query.hospital
      : null;
    let breadList = [
      { path: "/index", title: "首页" },
      {
        path: "/index/maintain/systemManagement/index",
        title: "帐号权限配置"
      },
      {
        path: "/index/maintain/admin/user/list",
        title: "账号管理"
      }
    ];
    this.$emit("changeBreadList", breadList);
      console.log(this.formValidate.passWord )
       console.log(this.passWord)
  },
  methods: {
    editBanner(param){
      this.editid = param
      this.uploadList = [];
      // 用户详情加载数据
      this.$axios
        .post(api.findUserById, {
          id: param
        })
        .then(res => {
          if (res.data.code) {
            let ret = res.data.object;
            this.formValidate.userName = ret.userName;
            this.formValidate.niceName = ret.nickName;
            this.formValidate.phone = ret.phone;
            this.switch1 = Boolean(Number(ret.status));
            this.text = ret.userName;
            this.passWord = ret.passWord;
            this.niceName = ret.nickName;
            this.identity = parseInt(ret.identity);
            this.provinceId = ret.provinceCode;
            this.cityId = ret.cityCode;
            this.areaId = ret.areaCode;
            this.hospitalId = ret.hospitalId;
            this.department = ret.department;
            if (this.identity == 1) {
            } else if (this.identity == 2) {
              this.provinceList.push(
                this.$store.getters.getProvinceById(ret.identityCoding)
              );
              this.provinceId = this.provinceList[0].id;
            } else if (this.identity == 3) {
              this.provinceList.push(
                this.$store.getters.getProvinceByCityId(ret.identityCoding)
              );
              this.provinceId = this.provinceList[0].id;
              this.cityList.push(
                this.$store.getters.getCityById(ret.identityCoding)
              );
              this.cityId = this.cityList[0].id;
            } else if (this.identity == 4) {
              this.areaList.push(
                this.$store.getters.getAreaById(ret.identityCoding)
              );
              this.areaId = this.areaList[0].id;
              this.cityList.push(
                this.$store.getters.getCityByAreaId(ret.identityCoding)
              );
              this.cityId = this.cityList[0].id;
              this.provinceList.push(
                this.$store.getters.getProvinceByCityId(this.cityId)
              );
              this.provinceId = this.provinceList[0].id;
            } else if (this.identity == 5) {
              this.provinceList = []
              this.cityList = []
              this.areaList = []
              this.areaList.push(
                this.$store.getters.getAreaById(this.areaId)
              );
              this.areaId = this.areaList[0].id;
              this.cityList.push(
                this.$store.getters.getCityByAreaId(this.areaId)
              );
              this.cityId = this.cityList[0].id;
              this.provinceList.push(
                this.$store.getters.getProvinceByCityId(this.cityId)
              );
              this.provinceId = this.provinceList[0].id;
              this.hospitalList = [
                { id: this.hospitalId, orgName: ret.hospitalName }
              ];
              //科室信息
              var params = {};
              params.hospitalId = parseInt(
                this.hospitalId == 0 ? null : this.hospitalId
              );
              this.$axios
                .post(api.departmentList, params)
                .then(resp => {
                  this.departmentList = resp.data.object;
                })
                .catch(err => {
                  console.log(err);
                });
            }
            //给科室下拉框赋值
            this.departmentList = [
              this.department
            ]
            if (Boolean(ret.userIcon)) {
              this.uploadList = []
              this.uploadList.push({
                name: "a42bdcc1178e62b4694c830f028db5c0",
                percentage: 100,
                status: "finished",
                uid: 1544263544971,
                url: this.fileBaseUrl + this.analysisImages(ret.userIcon)
              });
            }
            this.$refs.upload.fileList = this.uploadList
          } else {
            this.$Message.info("信息查询失败,请稍候重试");
          }
        });
    },
    // 弹出框关闭后触发
    handleClose(){
        // 子组件调用父组件方法，并传递参数
        this.$emit('changeShow','false')
    },
    onClose() {
      this.$emit('close')
    },
    inputFunc(){
      if(this.passWord.length>0){
        this.leng = false
        this.changer = 1
        this.formValidate.passWord = this.passWord
      }else{
        this.leng = true
        this.changer = 0
      }
    },
    handlePassword () {
        this.flag = !this.flag
    },
    save(name) {
      this.disabledSave = true
      let images = "";
      // 上传
      if (this.images != "") {
        images = this.images;
      } else if (this.sourceImages != "" && this.uploadList.length) {
        images = this.sourceImages;
        // 默认
      } else {
        images = "";
      }
      if(this.formValidate.passWord== ""||this.formValidate.passWord == null){
        if(this.formValidate.phone == "" || this.formValidate.phone == null){
          this.$Message.info("请输入用户手机号码");
          this.disabledSave = false
          return
        }
        // 必填项填写完成
            let params = {
              id: this.editid,
              //手机号
              phone:this.formValidate.phone,
              // 账号
              userName: this.formValidate.userName.trim(),
              //密码
              passWord: this.passWord,
              // 用户昵称
              nickName: this.formValidate.niceName.trim(),
              // 状态
              status: Number(this.switch1),
              // 用户头像
              userIcon: images
            };
              // 修改用户数据
              this.$axios.post(api.updatetUser, params).then(res => {
                if (res.data.code) {
                    let pageNo = this.$route.query.pageNo;
                    this.$Message.info("修改成功");
                    this.disabledSave = false
                    this.back()
                    // 当pageNo有值时它是从列表跳转过来的,需要跳回列表,值为空时,是从头像跳转过来的,跳转到主页面
                    // if (pageNo) {
                    //   setTimeout(() => {
                    //     this.disabledSave = false
                    //       // 公用方法
                    //     this.functionJS.queryNavgationTo(
                    //       this,
                    //       "/index/maintain/admin/user/list",
                    //       {
                    //         pageNo,
                    //         province: this.province,
                    //         city: this.city,
                    //         area: this.area,
                    //         hospital: this.hospital,
                    //         isBack: 2
                    //       }
                    //     );
                    //   }, 1000);
                    // } else {
                    //   this.disabledSave = false
                    // }
                  } else {
                    this.$Message.info("修改失败,请稍候重试");
                    this.disabledSave = false
                  }
          });
      }else{
        console.log('进入2')
        this.$refs[name].validate(valid => {
          if (valid) {
            if(this.formValidate.phone == "" || this.formValidate.phone == null){
              this.$Message.info("请输入用户手机号码");
              this.disabledSave = false
              return
            }
              // 必填项填写完成
              let params = {
                id: this.editid,
                //手机号
                phone:this.formValidate.phone.trim(),
                // 账号
                userName: this.formValidate.userName.trim(),
                //密码
                passWord: this.formValidate.passWord,
                // 用户昵称
                nickName: this.formValidate.niceName.trim(),
                // 状态
                status: Number(this.switch1),
                // 用户头像
                userIcon: images
              };
                // 修改用户数据
                this.$axios.post(api.updatetUser, params).then(res => {
                  if (res.data.code) {
                      let pageNo = this.$route.query.pageNo;
                      this.$Message.info("修改成功");
                      this.disabledSave = false
                      this.back()
                      // 当pageNo有值时它是从列表跳转过来的,需要跳回列表,值为空时,是从头像跳转过来的,跳转到主页面
                    } else {
                      this.$Message.info("修改失败,请稍候重试");
                      this.disabledSave = false
                    }
            });
            //  else {
            //   // 必填项填写失败
            //   this.$Message.error("请检查必填荐是否填写完整！");
            // }
          }else{
            this.disabledSave = false
          }
        })
      }
    },
    back() {
      this.clear(),
      this.$emit('showeditModal');
    },
    clear() {
      this.formValidate = {}
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      this.uploadList.splice(0, 1);
      this.images = '';
    },
    handleSuccess(res, file) {
      res = this.uploadFileDecrypt(res);
      if (res.success) {
        file.url = this.fileBaseUrl + res.object[0].fileName;
        this.images = JSON.stringify(res.object[0]);
        file.name = res.object[0].fileName;
      } else {
        this.$Message.info("上传失败,请重试");
      }
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "上传失败",
        desc: "文件格式错误"
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件过大",
        desc: `文件${file.name}过大，文件最大限制为2000KB`
      });
    },
    handleBeforeUpload(file) {
      const check = this.uploadList.length < 1;
      if (!check) {
        this.$Message.info("只能上传一张图片");
      }
      return check;
    },
    analysisImages(json) {
      try {
        json = JSON.parse(json);
        return json.fileName;
      } catch (error) {
        return "";
      }
    }
  },
};
</script>
<style lang="less" scoped>
.eye{
    width: 22px;
    height: 22px;
    margin: 0 0 0 -32px;
    position: relative;
    // z-index: 9999;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
// 关闭input文本框自动填充背景色黄色
input:-webkit-autofill {
  box-shadow: 0 0 0px 1000px white inset !important;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.w-select {
  width: 120px;
}
.w-select-hos {
  width: 130px;
}
.w-select-identity {
  width: 150px;
}
.edit {
	width:100%;
	background: #ffffff;
	box-sizing: border-box;
	.container {
		width: 100%;
		margin: 0 auto;
		.main{
			width: 98%;
			display: flex;
			flex-direction: column;
			margin: 10px auto;
			border: 1px solid #f0f0f0;
			box-shadow: 0 4px 3px #ebedf8;
			border-radius: 5px;
			margin-bottom: 20px;
			.title {
				font-size: 20px;
				padding-left: 15px;
				margin-bottom: 20px;
				color: #333;
				height: 40px;
				line-height: 40px;
				background: #ebedf8;
			}
			.box {
				// padding: 0 50px;
			}
		}
	}
}
</style>

